import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/messageWall")
public class MessageWallServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    // private List<Message> messageList = new ArrayList<>();
    // 从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 声明当前服务器响应数据格式
        resp.setContentType("application/json; charset=utf8");
        List<Message> messageList = null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.getWriter().write(objectMapper.writeValueAsString(messageList));
    }
    // 向服务器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        // messageList.add(message);
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.setStatus(200);
        System.out.println("提交数据成功!");
        System.out.println("from="+ message.getFrom() + " to="+ message.getTo() +
                " message="+ message.getMessage());
    }

    private List<Message> load() throws SQLException {
        // 1. 创建数据源
        /*DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("284013");*/

        DataSource dataSource = DBUtil.getDateSource();

        // 2.建立连接
        Connection connection = dataSource.getConnection();

        // 3.构造SQL
        String sql = "select * from message";

        // 4.执行SQL语句
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();

        // 5.遍历结果集合
        List<Message> messageList = new ArrayList<>();
        while(resultSet.next()){
            Message message = new Message();
            message.setFrom(resultSet.getString("from"));
            message.setTo(resultSet.getString("to"));
            message.setMessage(resultSet.getString("message"));
            messageList.add(message);
        }

        // 6. 关闭结果集
        statement.close();
        connection.close();
        return messageList;
    }

    private void save(Message message) throws SQLException {
        // 1. 创建数据源
        /*DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSl=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("284013");*/

        DataSource dataSource = DBUtil.getDateSource();

        // 2.建立连接
       Connection connection = dataSource.getConnection();

        // 3.构造SQL
        String sql = "insert into message values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,message.getFrom());
        statement.setString(2,message.getTo());
        statement.setString(3,message.getMessage());

        // 4.执行sql语句
        int ret = statement.executeUpdate();
        System.out.println("ret = "+ ret);

        // 5.关闭连接
        statement.close();
        connection.close();
    }
}
